<?php
namespace app\api\service;

use app\api\model\Order;
use app\api\model\wine\Dermember;
use app\common\service\BaseService;
use app\store\model\SystemConfig;
use think\facade\Db;

class Statistics extends BaseService{

    static private $startTime,$tomorrowTime;

    // 设置时间
    public static function setTime(){
        self::$startTime = date('Y-m-d');
        $startTimer = strtotime(self::$startTime);
        self::$tomorrowTime = date('Y-m-d',$startTimer + 86400);
    }

    // 交易额-今日直营收入
    public static function directIncome(int $user_id): int
    {
        return Order::where(['user_id' => $user_id, 'pay_status' => 20, 'order_status' => 30])
            ->whereBetweenTime('create_time',self::$startTime,self::$tomorrowTime)
            ->sum('pay_price');
    }

    // 交易额-今日下线收入
    public static function offlineIncome(int $user_id): int
    {
        // 获取下线用户
        $arr = [];
        $r = Dermember::where(['pid' => $user_id])->field('user_id')->select();
        foreach ($r as $user_id_son) {
            array_push($arr, $user_id_son);
        }
        $where[] = ['user_id', 'in', $arr];
        $where[] = ['pay_status', '=', 20];
        $where[] = ['order_status', '=', 30];
        return Order::where($where)
            ->whereBetweenTime('create_time',self::$startTime,self::$tomorrowTime)
            ->sum('pay_price');
    }

    // 交易额-今日总收入
    public static function allIncome(int $user_id){
        return self::directIncome($user_id) + self::offlineIncome($user_id);
    }

    // 今日新增商户 或 直营新增商户
    public static function merchantAdd(int $user_id = 0)
    {
        $where = [];
        if($user_id>0){
            $where['user_id'] = $user_id;
        }
        $where['is_delete'] = 0;
        return Dermember::where($where)
            ->whereBetweenTime('create_time', self::$startTime, self::$tomorrowTime)
            ->sum('id');
    }

    // 消费次数
    private static function saleNum(int $user_id): int
    {
        // 消费次数
        $r = Db::query("SELECT IFNULL(SUM(o2.total_num),0) AS num FROM yoshop_order o1 LEFT JOIN yoshop_order_goods o2 ON o1.order_id = o2.order_id WHERE o1.pay_status = 20 AND o1.order_status = 30 AND o1.user_id = {$user_id}");
        $num = 0;
        if (isset($r[0]['num'])) {
            $num = $r[0]['num'];
        }
        return $num;
    }

    // 达标数据
    public static function UpToStandard(int $user_id){
        // 今日新增经销商
        $referee_level = SystemConfig::getKeys('referee_level');// 直推人会员等级
        $referee_num = SystemConfig::getKeys('referee_num');// 直推会员数量
        $me_consume_num = SystemConfig::getKeys('me_consume_num');// 管理奖者消费次数
        $where = [
            ['is_delete','=',0],
            ['pcount','>=',$referee_num], // 达标团队人数
        ];
        $derList = Dermember::where($where)
            // 今日
            ->whereBetweenTime('create_time', self::$startTime, self::$tomorrowTime)
            ->with(['usergrade'=>function($query) use($referee_level){
                $query->where(['grade_id'=>$referee_level]);
            }])
            ->select();

        // 达标交易额的用户
        $total_trade_userId = [];
        foreach ($derList as $der){
            if($der['grade_id']!=null){
                $user_id_one = $der['user_id'];
                // 消费次数
                $num = self::saleNum($user_id_one);
                if($num>=$me_consume_num){
                    // 达标用户
                    array_push($total_trade_userId,$user_id_one);
                }
            }

        }

        // 达标销售额
        $total_trade = Dermember::where(['is_delete'=>0])
            ->whereIn('user_id',$total_trade_userId)
            ->sum('total_expend_money');
        // 自营达标销售额
        // 判断自己是否达标
        $my_trade = 0.0;
        if(in_array($user_id,$total_trade_userId)){
            $my_trade = Dermember::where(['is_delete'=>0,'user_id'=>$user_id])
                ->sum('total_expend_money');
        }
        // 下级达标销售额
        $r_user_id = Dermember::where(['is_delete'=>0,'pid'=>$user_id])->field('user_id')->select();
        // 判断下线是否达标
        $down_userId_arr = [];
        foreach ($r_user_id as $rItem){
            $rUserId = $rItem['user_id'];
            if(in_array($rUserId,$total_trade_userId)){
                array_push($down_userId_arr,$rUserId);
            }
        }
        $down_trade = Dermember::where(['is_delete'=>0])
            ->whereIn('user_id',$down_userId_arr)
            ->sum('total_expend_money');
        return [
            'total_trade' => $total_trade,
            'my_trade' => $my_trade,
            'down_trade' => $down_trade
        ];
    }
}
